package com.jerry.security.config;

import com.jerry.security.authentication.sms.SmsCodeAuthFilter;
import com.jerry.security.authentication.sms.SmsCodeAuthProvider;
import com.jerry.security.handler.MyAuthFailureHandler;
import com.jerry.security.handler.MyAuthSuccessHandler;
import com.jerry.security.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class MobileSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Autowired
    private MyAuthFailureHandler myAuthFailureHandler;
    @Autowired
    private MyAuthSuccessHandler myAuthSuccessHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        SmsCodeAuthFilter smsCodeAuthFilter = new SmsCodeAuthFilter();
        smsCodeAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthFilter.setAuthenticationSuccessHandler(myAuthSuccessHandler);
        smsCodeAuthFilter.setAuthenticationFailureHandler(myAuthFailureHandler);

        SmsCodeAuthProvider smsCodeAuthProvider = new SmsCodeAuthProvider();
        smsCodeAuthProvider.setUserDetailsService(myUserDetailsService);

        http.authenticationProvider(smsCodeAuthProvider)
                .addFilterAfter(smsCodeAuthFilter, UsernamePasswordAuthenticationFilter.class);

    }


}
